﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using AutoMapper;
using DataModels.User;
using DataServices.User.Dto;
using Module = Autofac.Module;

namespace DataServices
{
    public class AutoMapperModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterAssemblyTypes(Assembly.Load("DataServices"))
                    .Where(m => typeof(Profile).IsAssignableFrom(m) && !m.IsAbstract && m.IsPublic)
                    .As<Profile>();

            builder.Register(c => new MapperConfiguration(cfg =>
            {
                //8.1.1 之后不能用，不知道为什么
                //var profiles = c.Resolve<IEnumerable<Profile>>();
                //foreach (Profile profile in profiles)
                //{
                //    cfg.AddProfile(profile);
                //}

                //官方文档是这样子的
                cfg.CreateMap<UserEntity,UserDto>();

            })).AsSelf().SingleInstance();

            builder.Register(c => c.Resolve<MapperConfiguration>()
                    .CreateMapper(c.Resolve))
                .As<IMapper>()
                .InstancePerLifetimeScope();
        }
    }
}
